#include "looper.h"
#include "util.h"
#include <thread>
#include <iostream>
Looper::Looper() : interrupt(false)
{
}

Looper::~Looper()
{
}

void Looper::exit()
{
    this->interrupt = true;
}

  void Looper::postmessage(Msg msg){
    std::unique_lock<std::mutex>(queue_mutex);
    queue.push(std::move(msg));
    condition.notify_one();

  }

std::unique_lock<std::mutex> Looper::acquire_lock(){

    return std::unique_lock<std::mutex>(this->mutex);
}

void Looper::run()
{
    while (!interrupt)
    {
    auto lock= acquire_lock();
    if( this->queue.empty()){
      this->condition.wait(lock);
     }else{
        auto  msg =queue.front();
        queue.pop();

        BEGIN_EXCEPT
          msg.callback();
        END_EXCEPT;
     }

    }
}